// pages/balance/index.js
let formatTime = require('../../utils/util.js')
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    recordList: [],
    money: '0.00'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getMoney()
    this.getRechargeList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  toRecharge: function () {
    wx.navigateTo({
      url: "/pages/recharge/index"
    })
  },

/**
* 获取余额
*/
  getMoney: function () {
    let token = wx.getStorageSync('token')
    let that = this
    console.log('getmoney')
    wx.request({
      url: app.apiUrl('/user/money'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {

      },
      success: function (res) {
        console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showModal({
            title: '提示',
            content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            showCancel: false
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          that.setData({
            money: res.data.data.money.toFixed(2)
          })
        }

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        
      }
    })
  },

/**
* 获取余额明细
*/
  getRechargeList: function () {
    let token = wx.getStorageSync('token')
    let that = this
    console.log('getrechargelist')
    wx.request({
      url: app.apiUrl('/user/rechargelist'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {

      },
      success: function (res) {
        console.log(res.data)
        if (res.data.code >= app.globalData.successCode) {

          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else {
          for (var i = 0; i < res.data.data.length; i++) {
            res.data.data[i].time = formatTime.formatTime(new Date(res.data.data[i].created_at))
            res.data.data[i].name = '充值'
            res.data.data[i].type = '0' 
            res.data.data[i].money = res.data.data[i].money.toFixed(2)
          }
          that.setData({
            recordList: res.data.data
          })
        }

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {

      }
    })
  }

})